
from dvadmin.lycrontab.models import ScriptManager
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.viewset import CustomModelViewSet
from rest_framework.decorators import action
from dvadmin.utils.json_response import SuccessResponse
from dvadmin.utils.file import GetAllFile
from rest_framework import serializers

class ScriptManagerBasisSerializer(CustomModelSerializer):
    """
    脚本管理
    """
    class Meta:
        model = ScriptManager
        fields = "__all__"
        read_only_fields = ["id"]
class TreeScriptManagerSerializer(CustomModelSerializer):
    """
    前端菜单路由的简单序列化器
    """
    value = serializers.CharField(source="path")
    label = serializers.CharField(source="name")

    class Meta:
        model = ScriptManager
        fields = ('label', 'value')
        # like查询
        search_fields = ['name', 'label']
        # 查询

class BasisViewSet(CustomModelViewSet):
    """
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = ScriptManager.objects.all()
    serializer_class = ScriptManagerBasisSerializer
    extra_filter_backends = []
    @action(methods=['GET'], detail=False)
    def scan(self,requests):
        """用于一键扫描脚本"""
        file = GetAllFile()
        for i in file:
            if not self.queryset.filter(path=i).exists():
                self.queryset.create(path=i).save()
        return SuccessResponse(data={}, msg="获取成功")
    @action(methods=['GET'], detail=False)
    def treeSearch(self,request):
        """列表结构"""
        # elif 'id' in getdict.keys():
        #     queryset = queryset.filter(id__in=getdict['id'])

        getdict = request.query_params.dict()
        queryset = self.queryset
        if 'name' in getdict.keys():
            queryset = queryset.filter(name__contains=getdict['name'])
        # elif 'id' in getdict.keys():
        #     queryset = queryset.filter(id__in=getdict['id'])

        serializer = TreeScriptManagerSerializer(queryset, many=True, request=request)
        data = serializer.data
        return SuccessResponse(data=data, msg="获取成功")
